<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/27 0027
 * Time: 14:41
 */

namespace app\admin\controller;
use app\common\logic\Draw;
use app\common\model\DrawCustom;
use app\common\model\DrawRecord;
use app\common\model\Gift  as model;
use app\common\model\GiftRecord;
use app\common\service\DrawService;
use Qiniu\Auth;
use think\Db;
use think\Loader;

class Gift extends  Base
{


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 奖品列表
     */
    public function draw()
    {

        if (request()->isPost()){
            $model = new Draw();
            $price = input('post.price/a');
            $chance = input('post.chance/a');
            $remark = input('post.remark/a');
            $name = input('post.name/a');
            $giveChance = input('post.giveChance/a');
            $box4 = input('post.box4/a');
            $box5 = input('post.box5/a');
            $box6 = input('post.box6/a');
            $id = input('post.id/a');

            //2019-7-24新增单独一列保存
            $field = input('post.field');
            if ($field){
                foreach ($price as $k => $v){
                    $data[$k]['id'] = $id[$k];
                    $data[$k]['price'] = $v;
                    $data[$k][$field] = $$field[$k];
                }
                $result = $model->change($data);
            }else{
                foreach ($price as $k => $v){
                    $data[$k]['id'] = $id[$k];
                    $data[$k]['price'] = $v;
                    $data[$k]['chance'] = $chance[$k];
                    $data[$k]['remark'] = $remark[$k];
                    $data[$k]['giveChance'] = $giveChance[$k];
                    $data[$k]['name'] = $name[$k];
                    $data[$k]['box4'] = $box4[$k];
                    $data[$k]['box5'] = $box5[$k];
                    $data[$k]['box6'] = $box6[$k];
                }
                $result = $model->change($data);
            }

            if ($result){

                if ($field){
                    DrawService::delete($field);
                }else{
                    DrawService::delete('chance');
                    DrawService::delete('giveChance');
                    DrawService::delete('box4');
                    DrawService::delete('box5');
                    DrawService::delete('box6');
                }

                $this->success('修改成功');
            }
            $this->error($model->getError());
        }


        $where['status'] = 1;
        $where['type']   = 1;
        $rows = Db::name('draw')->where($where)->select();
        $map['status'] = 1;
        foreach ($rows as $k => $v){
            if ($v['type'] == 1){ //礼物
                $map['gift_id'] = $v['key'];
                $gift = Db::name('gift')->where($map)->find();
                if ($gift){
                    $rows[$k]['name'] = $gift['gift_name'];
                    $rows[$k]['price'] = $gift['price'];
                }else{
                    unset($rows[$k]);
                }
            }
        }

        $list = arr_sort($rows,'price');

        $this->assign([
            'title' => '奖品列表',
            'rows' => $list,
        ]);

        return view();

    }

    protected $class = [
        ['id'=>1,'name'=>'砸金蛋'],
        ['id'=>4,'name'=>'开铜宝箱'],
        ['id'=>5,'name'=>'开银宝箱'],
        ['id'=>6,'name'=>'开金宝箱'],
    ];


    /**
     * 中奖记录
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function draw_list()
    {

//        获取途径  1=>砸金蛋  2=>开铜宝箱 3=>开银宝箱 4=>开金宝箱
        $map = [];

        if(!empty(input('keyword'))){
            $map['u.nick_name|u.phone'] = ['like','%'.trim(input('keyword')).'%'];
            $where['u.nick_name|u.phone'] = ['like','%'.trim(input('keyword')).'%'];
        }



        $hammer_num   = Db::name('users')->alias('u')->where($map)->sum('hammer_num');
        $hammer_give  = Db::name('users')->alias('u')->where($map)->sum('hammer_give');


        if (!empty(input('startDate'))){
            if (empty(input('endDate'))){
                $map['a.create_time'] = ['> time',strtotime(input('startDate'))];
            }else{
                $map['a.create_time'] = ['between time',[strtotime(input('startDate')),strtotime(input('endDate').' 23:59:59')]];
            }
        }elseif (!empty(input('endDate'))){
            $map['a.create_time'] = ['<= time',strtotime(input('endDate').' 23:59:59')];
        }

        if (is_numeric(input('price'))){
            $map['a.price'] = ['>=',input('price')];
        }

        if(is_numeric(input('class'))){
            $map['a.class'] = input('class');
        }



        $model = new DrawRecord();

        $rows  = $model->getList($map);
        $total = $model->alias('a')
                ->join('users u','a.user_id = u.user_id','left')
                ->where($map)
                ->sum('total');
        $where['a.title'] = ['like','抽奖活动->%'];

        if ($where['u.nick_name|u.phone']){

            $use = Db::name('money_detail')
                ->alias('a')
                ->join('users u','a.user_id = u.user_id','left')
                ->where($where)
                ->sum('a.money');

        }else{

            $use = Db::name('money_detail')
                ->alias('a')
                ->where($where)
                ->sum('a.money');

        }

        //总抽奖次数
        $allNum = $model->alias('a')
            ->join('users u','a.user_id = u.user_id','left')
            ->where($map)
            ->sum('num');

        $this->assign([
            'hammer_give' => $hammer_give,
            'hammer_num'  => $hammer_num,
            'title'       => '中奖记录',
            'rows'        => $rows,
            'pageHTML'    => $rows->render(),
            'total'       => $total,
            'use'         => $use,
            'allNum'      => $allNum,
            'class'       => $this->class,
        ]);
        return view();
    }


    public function  index()
    {

        $map=[];
        if(!empty($_GET['gift_name'])){
            $map['gift_name'] = ['like','%'.trim(input('get.gift_name')).'%'];
        }
        if(!isEmpty($_GET['status'])){
            $map['status']=trim(input('get.status'));
        }

        $model = new model();
        $rows  = $model->giftListAdmin($map);
        $this->assign([
            'rows'=>$rows,
            'pageHTML'=>$rows->render()
        ]);
        return view();
    }

    //添加礼物类型
    public function  gift_edit()
    {
        if(request()->isPost())
        {
            $data = input('post.');
            $map['type'] = 1;
            $map['key']  = $data['id'];
            $data=request()->param();
            $draw = Db::name('draw')->where($map)->find();

            if ($data['is_draw'] == 1 && !$draw){ //参与抽奖
                $item['update_time'] = time();
                $item['chance'] = $data['chance'];
                $item['giveChance'] = $data['chance'];
                $item['box4'] = $data['chance'];
                $item['box5'] = $data['chance'];
                $item['box6'] = $data['chance'];
                $item['status'] = 1;
                if ($draw){
                    Db::name('draw')->where('id',$draw['id'])->update($item);
                }else{
                    $item['type'] = 1;
                    $item['key']  = $data['id'];
                    $item['create_time'] = time();
                    Db::name('draw')->insert($item);
                }
            }else{
                if ($draw){
                    $item['update_time'] = time();
                    $item['status'] = $data['is_draw'];
                    Db::name('draw')->where('id',$draw['id'])->update($item);
                }
            }
            $model=new model();
            $model->saveChange($data)?$this->success('成功',url('index')):$this->error('失败');

        }

        $gift_id = input('id');
        $details = db('gift')->where('gift_id',$gift_id)->find();
        $domain = config('qiniu')['domain'];
        $auth  = new Auth(config('qiniu')['ACCESSKEY'], config('qiniu')['SECRETKEY']);
        $token = $auth->uploadToken(config('qiniu')['bucket']);
        $this->assign([
            'data' => $details,
            'token' => $token,
            'domain' => $domain,
        ]);

        return view();
    }

    public function draw_custom()
    {
        $map = [];
        $model = new DrawCustom();
        $rows  = $model->getList($map);
        $this->assign([
            'rows'=>$rows,
            'pageHTML'=>$rows->render()
        ]);
        return view();
    }


    public function custom_edit()
    {

        if (request()->isPost()){
            $data  = input('post.');
            $model = new DrawCustom();
            //获取礼物key
            $data['key'] = Db::name('draw')->where('id',$data['draw_id'])->value('key');
            $result = $model->saveChange($data);
            if($result!==false){
                $this->success('保存成功','draw_custom');
            }
            $this->error('操作失败');
        }
        $map['type']   = 1;
        $map['status'] = 1;
        $gifts = Draw::where($map)->select();
        $this->assign(['gifts'=>$gifts]);
        $this->_find('draw_custom');
        return view();
    }

    public function change()
    {
        $this->_change('draw_custom');
    }

    
    //后台删除礼物
    public function  gift_delete(){
        $id = input('id');
        if (!is_numeric($id)) $this->error('参数错误');
        $result = Db::name('gift')->where('gift_id',$id)->delete();
        if ($result){
            $this->success('成功');
        }
        $this->error('失败');
    }

    //礼物赠送记录
    public  function  gift_record_list()
    {
        $map = [];
        if(!empty($_GET['gift_name'])){
            $map['g.gift_name'] = ['like','%'.trim(input('get.gift_name')).'%'];
        }
        if(!empty($_GET['startDate'])){
            $startDate = strtotime(trim(input('get.startDate')));
        }
        if(!empty($_GET['endDate'])){
            $endDate = strtotime(trim(input('get.endDate')));
        }
        if($startDate&&$endDate){
            $map['gr.create_time'] = ['between',$startDate,$endDate];
        }else if($startDate&&empty($endDate)){
            $map['gr.create_time'] = ['>',$startDate];
        }else if($endDate&&empty($startDate)){
            $map['gr.create_time'] = ['<',$endDate];
        }

        if (input('keyword')){
            $map['u.nick_name|u.phone'] = ['like','%'.trim(input('keyword')).'%'];
        }
        if (input('keyword2')){
            $map['tu.nick_name|tu.phone'] = ['like','%'.trim(input('keyword2')).'%'];
        }


        $model = new GiftRecord();

        if (input('download') == 'download'){ //点击了下载
            /* 永不超时 */
            ini_set('max_execution_time', 0);
            $rows = $model->downloadList($map);
            //         $path = ROOT_PATH.'public'.DS.'download'.DS.'excel'; //找到当前脚本所在路径
            Loader::import('PHPExcel.PHPExcel');//手动引入PHPExcel.php
//         Loader::import('PHPExcel.PHPExcel.IOFactory.PHPExcel_IOFactory');//引入IOFactory.php 文件里面的PHPExcel_IOFactory这个类
            $PHPExcel = new \PHPExcel();//实例化
            $PHPSheet = $PHPExcel->getActiveSheet();
            $PHPSheet->setTitle("礼物记录".date('Ymdhis')); //给当前活动sheet设置名称
            $PHPSheet->setCellValue("A1","id")//表格数据
            ->setCellValue("B1","礼物名称")
                ->setCellValue("C1","礼物价格")
                ->setCellValue("D1","赠送数量")
                ->setCellValue("E1","赠送人")
                ->setCellValue("F1","受赠人")
                ->setCellValue("G1","日期");
            if (empty($rows)) $this->error('暂无数据');
            $i = 1;
            foreach ($rows as $k => $v){
                $i++;
                $PHPSheet->setCellValue("A$i",$v['record_id'])
                    ->setCellValue("B$i",$v['gift_name'])
                    ->setCellValue("C$i",$v['num'])
                    ->setCellValue("D$i",$v['price'])
                    ->setCellValue("E$i",$v['nick_name'])
                    ->setCellValue("F$i",$v['to_user'])
                    ->setCellValue("G$i",$v['create_time']);
            }
            $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007");//创建生成的格式
            $date = date('Ymdhis');
            header('Content-Disposition: attachment;filename="礼物记录'.$date.'.xlsx"');//下载下来的表格名
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
            exit;

        }

        $rows  = $model->recordList($map);
        $this->assign([
            'rows'=>$rows,
            'pageHTML'=>$rows->render()
        ]);
        return view();
    }
}